#include "citycodeutils.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QMessageBox>

CityCodeUtils::CityCodeUtils()
{

}

QString CityCodeUtils::getCityCoudeFromName(QString cityName)
{
    //当用户第一次搜索时初始化本地城市代码表
    if(cityMap.isEmpty())
    {
        initCityMap();
    }
    //为应对用户没输入准确的地区名称，如蚌埠时，依然能搜索到结果（蚌埠县）
    QMap<QString,QString>::iterator it = cityMap.find(cityName);
    if(it == cityMap.end())
    {
        it = cityMap.find(cityName +"市");
        if(it == cityMap.end())
        {
            it = cityMap.find(cityName +"县");
            if(it == cityMap.end())
            {
                it = cityMap.find(cityName +"区");
                if(it == cityMap.end())
                {
                    return "";
                }
            }
        }
    }

    return it.value();
}

void CityCodeUtils::initCityMap()
{
    QFile file(":/citycode.json");
    file.open(QIODevice::ReadOnly);
    //获取原始数据
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray())
    {
        QJsonArray citys = jsonDoc.array();
        for(QJsonValue value : citys)
        {
            //将原始数据的城市名和城市代码提取出来并装载到cityMap中
            if(value.isObject())
            {
                QString findedcityName = value["city_name"].toString();
                QString cityCode = value["city_code"].toString();
                cityMap.insert(findedcityName,cityCode);
            }
        }
    }
}
